package com.ruoyi.ftrl.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.ftrl.domain.*;
import com.ruoyi.ftrl.mapper.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.ftrl.service.IAreasInfoService;

/**
 * 片区信息Service业务层处理
 * 
 * @author 邸航
 * @date 2024-08-05
 */
@Service
@Slf4j
public class AreasInfoServiceImpl implements IAreasInfoService 
{

    @Autowired
    private AreasInfoMapper areasInfoMapper;
    @Autowired
    private HeatStationMapper heatStationMapper;
    @Autowired
    private EquipmentDockingMapper equipmentDockingMapper;
    @Autowired
    private CommunityInfoMapper communityInfoMapper;

    /**
     * 查询片区信息
     * 
     * @param id 片区信息主键
     * @return 片区信息
     */
    @Override
    public AreasInfo selectAreasInfoById(Long id)
    {
        return areasInfoMapper.selectAreasInfoById(id);
    }

    /**
     * 查询片区信息列表
     * 
     * @param areasInfo 片区信息
     * @return 片区信息
     */
    @Override
    public List<AreasInfo> selectAreasInfoList(AreasInfo areasInfo)
    {
        return areasInfoMapper.selectAreasInfoList(areasInfo);
    }

    /**
     * 新增片区信息
     * 
     * @param areasInfo 片区信息
     * @return 结果
     */
    @Override
    public int insertAreasInfo(AreasInfo areasInfo)
    {
        areasInfo.setCreateTime(DateUtils.getNowDate());
        return areasInfoMapper.insertAreasInfo(areasInfo);
    }

    /**
     * 修改片区信息
     * 
     * @param areasInfo 片区信息
     * @return 结果
     */
    @Override
    public int updateAreasInfo(AreasInfo areasInfo)
    {
        areasInfo.setUpdateTime(DateUtils.getNowDate());
        return areasInfoMapper.updateAreasInfo(areasInfo);
    }

    /**
     * 批量删除片区信息
     * 
     * @param ids 需要删除的片区信息主键
     * @return 结果
     */
    @Override
    public int deleteAreasInfoByIds(Long[] ids)
    {
        return areasInfoMapper.deleteAreasInfoByIds(ids);
    }

    /**
     * 删除片区信息信息
     * 
     * @param id 片区信息主键
     * @return 结果
     */
    @Override
    public int deleteAreasInfoById(Long id)
    {
        return areasInfoMapper.deleteAreasInfoById(id);
    }
    @Autowired
    private EquipmentHeatMapper equipmentHeatMapper;
    @Autowired
    private TemperatureControlMapper temperatureControlMapper;
    /**
     * 查询片区列表以及各个片区下的子级热力站以及各个设备数量（水力平衡页面）
     */
    @Override
    public List<AreasInfo> selectAreasInfoListAll(String name) {
        if (name == null || "".equals(name)) {
            List<AreasInfo> list = areasInfoMapper.selectAreasInfoListAll();
            for (AreasInfo areasInfo : list) {
                long hotCount = 0L;    // 热表数量
                long flowCount = 0L;   // 平衡阀数量
                long lockCount = 0L;   // 锁闭阀数量
                long unitCount = 0L;   // 单元阀数量
                long tempCount = 0L;   // 室温采集器数量

                List<HeatStation> heatStations = heatStationMapper.selectHeatStationLists(areasInfo.getId());
                for (HeatStation heatStation : heatStations) {
                    List<CommunityInfo> communityInfoList = communityInfoMapper.selectCommunityInfoLists(heatStation.getId());

                    // 获取小区ID集合
                    List<Long> ids = communityInfoList.stream()
                            .filter(community -> community != null)
                            .map(CommunityInfo::getId)
                            .filter(Objects::nonNull)
                            .toList();

                    if (!ids.isEmpty()) {
                        // 批量查询热表数量
                        List<EquipmentHeat> equipmentHeats = equipmentHeatMapper.selectEquipmentHeatListByIds(ids);
                        heatStation.setHotCount((long) equipmentHeats.size());
                        hotCount = hotCount + equipmentHeats.size();

                        // 批量查询阀门数据
                        List<TemperatureControl> temperatureControls = temperatureControlMapper.selectTemperatureControlListByIds(ids);

                        // 平衡阀数量
//                        long count = temperatureControls.stream()
//                                .filter(temperatureControl -> "0".equals(temperatureControl.getDeviceType()))
//                                .count();
                        Long count=temperatureControlMapper.countDevicesByType(ids,"0");
                        heatStation.setFlowCount(count);
                        flowCount = flowCount + count;

                        // 锁闭阀数量
//                        long count1 = temperatureControls.stream()
//                                .filter(temperatureControl -> "1".equals(temperatureControl.getDeviceType()))
//                                .count();
                        Long count1=temperatureControlMapper.countDevicesByType(ids,"1");
                        heatStation.setLockCount(count1);
                        lockCount = lockCount + count1;

                        // 单元阀数量
//                        long count2 = temperatureControls.stream()
//                                .filter(temperatureControl -> "2".equals(temperatureControl.getDeviceType()))
//                                .count();
                        Long count2=temperatureControlMapper.countDevicesByType(ids,"2");
                        heatStation.setUnitCount(count2);
                        unitCount = unitCount + count2;
                    }

                    // 批量查询室温采集器
                    List<String> names = communityInfoList.stream()
                            .filter(community -> community != null)
                            .map(CommunityInfo::getName)
                            .filter(Objects::nonNull)
                            .toList();

                    if (!names.isEmpty()) {
                        List<EquipmentDocking> equipmentDockingList = equipmentDockingMapper.selectByCommunityNamess(names);
                        heatStation.setTempCount((long) equipmentDockingList.size());
                        tempCount = tempCount + equipmentDockingList.size();
                    }
                }

                // 设置片区统计数据
                areasInfo.setHeatStations(heatStations);
                areasInfo.setTempCount(tempCount);
                areasInfo.setFlowCount(flowCount);
                areasInfo.setLockCount(lockCount);
                areasInfo.setUnitCount(unitCount);
                areasInfo.setHotCount(hotCount);
            }
            return list;

        }
        List<AreasInfo> list = new ArrayList<>();
        List<HeatStation> heatStation = heatStationMapper.selectHeatStationByName(name);

        for (HeatStation station : heatStation) {
            String areaId = station.getAreaId();
            if (areaId != null && !"".equals(areaId)) {
                Long areaIdLong = Long.parseLong(areaId);
                AreasInfo areasInfo = areasInfoMapper.selectAreasInfoById(areaIdLong);

                // 初始化计数器
                long hotCount = 0L;    // 热表数量
                long flowCount = 0L;   // 平衡阀数量
                long lockCount = 0L;   // 锁闭阀数量
                long unitCount = 0L;   // 单元阀数量
                long tempCount = 0L;   // 室温采集器数量

                // 获取该热力站下的所有小区
                List<CommunityInfo> communityInfoList = communityInfoMapper.selectCommunityInfoLists(station.getId());

                // 获取小区ID集合
                List<Long> ids = communityInfoList.stream()
                        .filter(community -> community != null)
                        .map(CommunityInfo::getId)
                        .filter(Objects::nonNull)
                        .toList();

                if (!ids.isEmpty()) {
                    // 批量查询热表数量
                    List<EquipmentHeat> equipmentHeats = equipmentHeatMapper.selectEquipmentHeatListByIds(ids);
                    station.setHotCount((long) equipmentHeats.size());
                    hotCount = equipmentHeats.size();

                    // 批量查询阀门数据
                    List<TemperatureControl> temperatureControls = temperatureControlMapper.selectTemperatureControlListByIds(ids);

                    // 平衡阀数量
//                    long count = temperatureControls.stream()
//                            .filter(temperatureControl -> "0".equals(temperatureControl.getDeviceType())).toList().size();

                    Long count=temperatureControlMapper.countDevicesByType(ids,"0");
                    station.setFlowCount(count);
                    flowCount = count;

                    // 锁闭阀数量
//                    long count1 = temperatureControls.stream()
//                            .filter(temperatureControl -> "1".equals(temperatureControl.getDeviceType()))
//                            .count();
                    Long count1=temperatureControlMapper.countDevicesByType(ids,"1");
                    station.setLockCount(count1);
                    lockCount = count1;

                    // 单元阀数量
//                    long count2 = temperatureControls.stream()
//                            .filter(temperatureControl -> "2".equals(temperatureControl.getDeviceType()))
//                            .count();
                    Long count2=temperatureControlMapper.countDevicesByType(ids,"2");
                    station.setUnitCount(count2);
                    unitCount = count2;
                }

                // 批量查询室温采集器
                List<String> names = communityInfoList.stream()
                        .filter(community -> community != null)
                        .map(CommunityInfo::getName)
                        .filter(Objects::nonNull)
                        .toList();

                if (!names.isEmpty()) {
                    List<EquipmentDocking> equipmentDockingList = equipmentDockingMapper.selectByCommunityNamess(names);
                    station.setTempCount((long) equipmentDockingList.size());
                    tempCount = equipmentDockingList.size();
                }

                // 设置热力站列表
                List<HeatStation> stationList = new ArrayList<>();
                stationList.add(station);
                areasInfo.setHeatStations(stationList);

                // 设置片区统计数据
                areasInfo.setTempCount(tempCount);
                areasInfo.setFlowCount(flowCount);
                areasInfo.setLockCount(lockCount);
                areasInfo.setUnitCount(unitCount);
                areasInfo.setHotCount(hotCount);

                list.add(areasInfo);
            }
        }
        return list;
    }

    /**
     * 供热质量查询片区列表以及各个片区下的子级热力站的平均温度
     */
//    @Override
//    public List<AreasInfo> selectAreasInfoListAlls(String name) {
//        if (name == null || "".equals(name)) {
//            List<AreasInfo> list = areasInfoMapper.selectAreasInfoListAll();
//            for (AreasInfo areasInfo : list) {
//                List<HeatStation> heatStations = heatStationMapper.selectHeatStationLists(areasInfo.getId());
//                if (!heatStations.isEmpty()) {  // 添加检查
//                    for (HeatStation heatStation : heatStations) {
//                        Double sum = 0.00;
//                        Long id = heatStation.getId();
//                        List<CommunityInfo> communityInfoList = communityInfoMapper.selectCommunityInfoLists(id);
//                        if (!communityInfoList.isEmpty()) {  // 添加检查
//                            int validCount = 0;  // 记录有效温度数据的数量
//                            for (CommunityInfo communityInfo : communityInfoList) {
//                                EquipmentDocking equipmentDocking = equipmentDockingMapper.selectByNameAvg(communityInfo.getName());
//                                if (equipmentDocking != null && equipmentDocking.getAverageTemperature() != null) {
//                                    try {
//                                        Double averageTemperatureLong = Double.valueOf(equipmentDocking.getAverageTemperature());
//                                        sum += averageTemperatureLong;
//                                        validCount++;
//                                    } catch (NumberFormatException ignored) {
//
//                                    }
//                                }
//                            }
//                            // 只在有有效数据时计算平均值
//                            if (validCount > 0) {
//                                Double avgTemp = sum / validCount;
//                                heatStation.setAverageTemperature(String.format("%.2f", avgTemp));
//                            } else {
//                                heatStation.setAverageTemperature("0.00");
//                            }
//                            heatStation.setCommunityId(communityInfoList.get(0).getId());
//                        } else {
//                            heatStation.setAverageTemperature("0.00");
//                        }
//                    }
//
//                    // 计算片区平均温度
//                    if (!heatStations.isEmpty()) {
//                        double totalTemperature = 0;
//                        int validStations = 0;
//                        for (HeatStation station : heatStations) {
//                            try {
//                                double temp = Double.parseDouble(station.getAverageTemperature());
//                                if (temp > 0) {  // 只计算有效温度
//                                    totalTemperature += temp;
//                                    validStations++;
//                                }
//                            } catch (NumberFormatException ignored) {
//
//                            }
//                        }
//                        double avg = validStations > 0 ? totalTemperature / validStations : 0;
//                        areasInfo.setAverageTemperature(String.format("%.2f", avg));
//                    } else {
//                        areasInfo.setAverageTemperature("0.00");
//                    }
//                }
//                areasInfo.setHeatStations(heatStations);
//            }
//            return list;
//        }
//
//        // 处理按名称搜索的情况
//        List<AreasInfo> list = new ArrayList<>();
//        List<HeatStation> heatStation = heatStationMapper.selectHeatStationByName(name);
//        if (!heatStation.isEmpty()) {  // 添加检查
//            for (HeatStation station : heatStation) {
//                Double sum = 0.00;
//                Long id = station.getId();
//                List<CommunityInfo> communityInfoList = communityInfoMapper.selectCommunityInfoLists(id);
//                if (!communityInfoList.isEmpty()) {  // 添加检查
//                    int validCount = 0;
//                    for (CommunityInfo communityInfo : communityInfoList) {
//                        EquipmentDocking equipmentDocking = equipmentDockingMapper.selectByNameAvg(communityInfo.getName());
//                        if (equipmentDocking != null && equipmentDocking.getAverageTemperature() != null) {
//                            try {
//                                Double averageTemperatureLong = Double.valueOf(equipmentDocking.getAverageTemperature());
//                                sum += averageTemperatureLong;
//                                validCount++;
//                            } catch (NumberFormatException ignored) {
//
//                            }
//                        }
//                    }
//
//                    if (validCount > 0) {
//                        Double avgTemp = sum / validCount;
//                        station.setAverageTemperature(String.format("%.2f", avgTemp));
//                    } else {
//                        station.setAverageTemperature("0.00");
//                    }
//                    station.setCommunityId(communityInfoList.get(0).getId());
//
//                    String areaId = station.getAreaId();
//                    if (areaId != null && !areaId.isEmpty()) {
//                        try {
//                            Long areaIdLong = Long.parseLong(areaId);
//                            AreasInfo areasInfo = areasInfoMapper.selectAreasInfoById(areaIdLong);
//                            if (areasInfo != null) {
//                                List<HeatStation> stationList = new ArrayList<>();
//                                stationList.add(station);
//                                areasInfo.setHeatStations(stationList);
//                                list.add(areasInfo);
//                            }
//                        } catch (NumberFormatException ignored) {
//
//                        }
//                    }
//                }
//            }
//
//            // 计算片区平均温度
//            for (AreasInfo areasInfo : list) {
//                List<HeatStation> stations = areasInfo.getHeatStations();
//                if (stations != null && !stations.isEmpty()) {
//                    double totalTemperature = 0;
//                    int validStations = 0;
//                    for (HeatStation station : stations) {
//                        try {
//                            double temp = Double.parseDouble(station.getAverageTemperature());
//                            if (temp > 0) {
//                                totalTemperature += temp;
//                                validStations++;
//                            }
//                        } catch (NumberFormatException ignored) {
//
//                        }
//                    }
//                    double avg = validStations > 0 ? totalTemperature / validStations : 0;
//                    areasInfo.setAverageTemperature(String.format("%.2f", avg));
//                } else {
//                    areasInfo.setAverageTemperature("0.00");
//                }
//            }
//        }
//        return list;
//
//
//
//
//
////        if (name == null || "".equals(name)){
////            List<AreasInfo>list=areasInfoMapper.selectAreasInfoListAll();
////            for (AreasInfo areasInfo : list) {
////                List<HeatStation> heatStations = heatStationMapper.selectHeatStationLists(areasInfo.getId());
////                Double sum=0.00;
////                for (HeatStation heatStation : heatStations) {
////                    //热力站ID
////                    Long id = heatStation.getId();
////                    //每个热力站的平均温度
////                    List<CommunityInfo> communityInfoList = communityInfoMapper.selectCommunityInfoLists(id);
////                    for (CommunityInfo communityInfo : communityInfoList) {
////                        EquipmentDocking equipmentDocking=equipmentDockingMapper.selectByNameAvg(communityInfo.getName());
////                        if (equipmentDocking!=null){
////                            String averageTemperature = equipmentDocking.getAverageTemperature();
////                            Double averageTemperatureLong=Double.valueOf(averageTemperature);
////                            sum=sum+averageTemperatureLong;
////                        }
////                    }
////                    Double sun2 = sum / communityInfoList.size();
////                    //热力站平均温度（包括了一个热力站含有多个小区的情况）
////                    heatStation.setAverageTemperature(String.valueOf(sun2));
////                    heatStation.setCommunityId(communityInfoList.get(0).getId());
////
////                }
////                areasInfo.setHeatStations(heatStations);
////
////                //计算每个片区的平均温度
////                double totalTemperature = heatStations.stream()
////                        .map(HeatStation::getAverageTemperature) // 获取温度字段（String）
////                        .mapToDouble(Double::parseDouble) // 将字符串转换为 double
////                        .sum();
////                double avg = totalTemperature / heatStations.size();
////                areasInfo.setAverageTemperature(String.valueOf(avg));
////
////            }
////            return list;
////        }
////        List<AreasInfo>list=new ArrayList<AreasInfo>();
////        List<HeatStation> heatStation=heatStationMapper.selectHeatStationByName(name);
////        Double sun=0.00;
////        for (HeatStation station : heatStation) {
////            //热力站ID
////            Long id = station.getId();
////            //每个热力站的平均温度
////            List<CommunityInfo> communityInfoList = communityInfoMapper.selectCommunityInfoLists(id);
////            for (CommunityInfo communityInfo : communityInfoList) {
////                EquipmentDocking equipmentDocking=equipmentDockingMapper.selectByNameAvg(communityInfo.getName());
////                if (equipmentDocking!=null){
////                    String averageTemperature = equipmentDocking.getAverageTemperature();
////                    Double averageTemperatureLong=Double.valueOf(averageTemperature);
////                    sun=sun+averageTemperatureLong;
////                }
////            }
////            Double sun1 = sun / communityInfoList.size();
////          //热力站平均温度（包括了一个热力站含有多个小区的情况）
////            station.setAverageTemperature(String.valueOf(sun1));
////            station.setCommunityId(communityInfoList.get(0).getId());
////
////            String areaId = station.getAreaId();
////            if (areaId!=null&&!"".equals(areaId)){
////                Long areaIdLong=Long.parseLong(areaId);
////                AreasInfo areasInfo = areasInfoMapper.selectAreasInfoById(areaIdLong);
////                List<HeatStation> stationList=new ArrayList<>();
////                stationList.add(station);
////                areasInfo.setHeatStations(stationList);
////                list.add(areasInfo);
////            }
////            for (AreasInfo areasInfo : list) {
////                //计算每个片区的平均温度
////                double totalTemperature = heatStation.stream()
////                        .map(HeatStation::getAverageTemperature) // 获取温度字段（String）
////                        .mapToDouble(Double::parseDouble) // 将字符串转换为 double
////                        .sum();
////                double avg = totalTemperature / heatStation.size();
////                areasInfo.setAverageTemperature(String.valueOf(avg));
////            }
////
////        }
////        return list;
//    }

    private static final BigDecimal STANDARD_TEMPERATURE = new BigDecimal("18.0"); // 达标温度标准
    @Override
    public List<AreasInfo> selectAreasInfoListAlls(String name) {
        List<AreasInfo> resultList = new ArrayList<>();
        try {
            if (name == null || "".equals(name)) {
                resultList = processAllAreas();
            } else {
                resultList = processAreasByName(name);
            }
        } catch (Exception e) {
//            log.error("查询片区信息异常", e);
        }
        return resultList;
    }

    /**
     * 处理所有片区数据
     */
    private List<AreasInfo> processAllAreas() {
        // 1. 获取所有片区
        List<AreasInfo> areasList = areasInfoMapper.selectAreasInfoListAll();
        if (areasList.isEmpty()) {
            return Collections.emptyList();
        }

        // 2. 批量获取所有热力站
        List<Long> areaIds = areasList.stream()
                .map(AreasInfo::getId)
                .collect(Collectors.toList());
        List<HeatStation> allStations = heatStationMapper.batchSelectHeatStationsByAreaIds(areaIds);

        // 3. 批量获取所有小区
        List<Long> stationIds = allStations.stream()
                .map(HeatStation::getId)
                .collect(Collectors.toList());
        List<CommunityInfo> allCommunities = communityInfoMapper.batchSelectCommunityInfoByStationIds(stationIds);
        System.err.println("获取到的小区实体为："+allCommunities);

        // 4. 批量获取所有温度数据
        List<String> communityNames = allCommunities.stream()
                .map(CommunityInfo::getName)
                .collect(Collectors.toList());
        System.err.println("获取到的小区名称为："+communityNames);
        Map<String, TemperatureStats> temperatureStatsMap = getTemperatureStats(communityNames);

        // 5. 组装数据
        return assembleAreasData(areasList, allStations, allCommunities, temperatureStatsMap);
    }

    /**
     * 根据名称处理片区数据
     */
    private List<AreasInfo> processAreasByName(String name) {
        // 1. 获取匹配的热力站
        List<HeatStation> matchedStations = heatStationMapper.selectHeatStationByName(name);
        if (matchedStations.isEmpty()) {
            return Collections.emptyList();
        }

        // 2. 批量获取小区信息
        List<Long> stationIds = matchedStations.stream()
                .map(HeatStation::getId)
                .collect(Collectors.toList());
        List<CommunityInfo> communities = communityInfoMapper.batchSelectCommunityInfoByStationIds(stationIds);
        System.err.println("获取到的小区信息：" + communities);

        // 3. 批量获取温度数据
        List<String> communityNames = communities.stream()
                .map(CommunityInfo::getName)
                .collect(Collectors.toList());
        Map<String, TemperatureStats> temperatureStatsMap = getTemperatureStats(communityNames);
        System.err.println("获取到的温度统计数据：" + temperatureStatsMap);

        // 4. 获取相关的片区信息
        Set<Long> areaIds = matchedStations.stream()
                .map(station -> Long.parseLong(station.getAreaId()))
                .collect(Collectors.toSet());
        List<AreasInfo> areas = areasInfoMapper.batchSelectAreasInfoByIds(new ArrayList<>(areaIds));

        // 5. 为每个片区处理数据
        for (AreasInfo area : areas) {
            // 过滤出属于当前片区的匹配热力站
            List<HeatStation> areaMatchedStations = matchedStations.stream()
                    .filter(station -> station.getAreaId() != null &&
                            Long.parseLong(station.getAreaId()) == area.getId())
                    .collect(Collectors.toList());

            // 设置片区的热力站列表
            area.setHeatStations(areaMatchedStations);
            if (!areaMatchedStations.isEmpty()) {
                area.setHeatStation(areaMatchedStations.get(0));
            }

            // 片区统计数据
            double areaTotalTemp = 0.0;
            double areaTotalStandardRate = 0.0;
            double areaTotalNonStandardRate = 0.0;
            int validStationCount = 0;

            // 处理每个热力站
            for (HeatStation station : areaMatchedStations) {
                Long id1 = area.getId();
                station.setAreaId(String.valueOf(id1));
                // 获取该热力站的所有小区
//                List<CommunityInfo> stationCommunities = communities.stream()
//                        .filter(community -> community.getHeatId() != null &&
//                                community.getHeatId().equals(station.getId()))
//                        .collect(Collectors.toList());
                List<CommunityInfo> stationCommunities=communityInfoMapper.selectCommunityInfoLists(station.getId());

                System.err.println("热力站 " + station.getName() + " 关联的小区数量: " + stationCommunities.size());

                // 计算热力站统计数据
                double stationTotalTemp = 0.0;
                double stationTotalStandardRate = 0.0;
                double stationTotalNonStandardRate = 0.0;
                int validCommunityCount = 0;

                // 处理每个小区的温度数据
                for (CommunityInfo community : stationCommunities) {
                    TemperatureStats stats = temperatureStatsMap.get(community.getName());
                    if (stats != null && stats.getAverageTemperature() > 0) {
                        stationTotalTemp += stats.getAverageTemperature();
                        stationTotalStandardRate += stats.getStandardRate();
                        stationTotalNonStandardRate += stats.getNonStandardRate();
                        validCommunityCount++;
                        System.err.println("小区 " + community.getName() + " 的温度数据: " + stats.getAverageTemperature());
                    }
                }

                // 设置热力站统计数据
                if (validCommunityCount > 0) {
                    double avgTemp = stationTotalTemp / validCommunityCount;
                    double avgStandardRate = stationTotalStandardRate / validCommunityCount;
                    double avgNonStandardRate = stationTotalNonStandardRate / validCommunityCount;

                    station.setAverageTemperature(String.format("%.2f", avgTemp));
                    station.setStandardRate(String.format("%.2f", avgStandardRate));
                    station.setNonStandardRate(String.format("%.2f", avgNonStandardRate));

                    // 累加到片区统计
                    areaTotalTemp += avgTemp;
                    areaTotalStandardRate += avgStandardRate;
                    areaTotalNonStandardRate += avgNonStandardRate;
                    validStationCount++;

                    System.err.println("热力站 " + station.getName() + " 统计数据 - 平均温度: " +
                            station.getAverageTemperature() + ", 达标率: " + station.getStandardRate());
                } else {
                    station.setAverageTemperature("0.00");
                    station.setStandardRate("0.00");
                    station.setNonStandardRate("0.00");
                    System.err.println("热力站 " + station.getName() + " 没有有效的温度数据");
                }
            }

            // 设置片区统计数据
            if (validStationCount > 0) {
                String avgTemp = String.format("%.2f", areaTotalTemp / validStationCount);
                String avgStandardRate = String.format("%.2f", areaTotalStandardRate / validStationCount);
                String avgNonStandardRate = String.format("%.2f", areaTotalNonStandardRate / validStationCount);

                area.setAverageTemperature(avgTemp);
                area.setStandardRate(avgStandardRate);
                area.setNonStandardRate(avgNonStandardRate);

                System.err.println("片区 " + area.getName() + " 统计数据 - 平均温度: " +
                        avgTemp + ", 达标率: " + avgStandardRate);
            } else {
                area.setAverageTemperature("0.00");
                area.setStandardRate("0.00");
                area.setNonStandardRate("0.00");
                System.err.println("片区 " + area.getName() + " 没有有效的统计数据");
            }
        }

        return areas;
    }

    /**
     * 获取温度统计数据
     */
    private Map<String, TemperatureStats> getTemperatureStats(List<String> communityNames) {
        if (communityNames.isEmpty()) {
            log.warn("小区名称列表为空");
            return Collections.emptyMap();
        }

        log.warn("开始查询温度数据，小区数量: {}", communityNames.size());
        log.warn("小区名称列表: {}", communityNames);

        List<EquipmentDocking> temperatureData = equipmentDockingMapper.selectByCommunityNames(communityNames);
        System.err.println("获取到的室温实体数据为：" + temperatureData);

        // 检查温度数据
        temperatureData.forEach(data ->
                System.err.println("小区: " + data.getVillageName() + ", 温度: " + data.getTemp())
        );

        // 使用有效数据进行分组和计算
        Map<String, TemperatureStats> collect = temperatureData.stream()
                .collect(Collectors.groupingBy(
                        EquipmentDocking::getVillageName,
                        Collectors.collectingAndThen(
                                Collectors.toList(),
                                this::calculateTemperatureStats
                        )
                ));

        System.err.println("统计结果数量：" + collect.size());
        // 打印统计结果示例
        collect.forEach((villageName, stats) ->
                System.err.println("小区: " + villageName +
                        ", 平均温度: " + stats.getAverageTemperature() +
                        ", 达标率: " + stats.getStandardRate() +
                        ", 不达标率: " + stats.getNonStandardRate())
        );

        return collect;
    }

    /**
     * 计算温度统计信息
     */
    private TemperatureStats calculateTemperatureStats(List<EquipmentDocking> records) {
        if (records.isEmpty()) {
            return new TemperatureStats(0.0, 0.0, 0.0);
        }

        System.err.println("开始计算统计信息，记录数：" + records.size());

        long totalCount = records.size();
        long standardCount = records.stream()
                .filter(r -> {
                    try {
                        return r.getTemp() != null &&
                                r.getTemp().compareTo(STANDARD_TEMPERATURE) >= 0;
                    } catch (Exception e) {
                        log.error("温度比较异常：" + r.getTemp(), e);
                        return false;
                    }
                })
                .count();

        double averageTemp = records.stream()
                .map(EquipmentDocking::getTemp)
                .filter(Objects::nonNull)
                .mapToDouble(BigDecimal::doubleValue)
                .average()
                .orElse(0.0);

        System.err.println("计算结果 - 总数: " + totalCount +
                ", 达标数: " + standardCount +
                ", 平均温度: " + averageTemp);

        return new TemperatureStats(
                averageTemp,
                calculateRate(standardCount, totalCount),
                calculateRate(totalCount - standardCount, totalCount)
        );
    }

    /**
     * 计算比率
     */
    private double calculateRate(long part, long total) {
        return total == 0 ? 0.0 : (double) part / total * 100;
    }

    /**
     * 组装数据
     */
//    private List<AreasInfo> assembleAreasData(
//            List<AreasInfo> areas,
//            List<HeatStation> stations,
//            List<CommunityInfo> communities,
//            Map<String, TemperatureStats> communityStats) {
//
//        log.warn("开始组装数据 - 片区数量: {}, 热力站数量: {}, 小区数量: {}, 温度统计数量: {}",
//                areas.size(), stations.size(), communities.size(), communityStats.size());
//
//        try {
//            // 1. 按片区ID分组热力站
//            Map<Long, List<HeatStation>> stationsByArea = stations.stream()
//                    .filter(station -> station.getAreaId() != null)
//                    .collect(Collectors.groupingBy(station -> Long.parseLong(station.getAreaId())));
//
//            // 2. 处理每个片区
//            for (AreasInfo area : areas) {
//                log.warn("处理片区: {}", area.getId());
//
//                // 获取该片区的所有热力站
//                Long id = area.getId();
//                List<HeatStation> areaStations = heatStationMapper.selectHeatStationsByAreaId(id);
//                log.warn("片区 {} 的热力站数量: {}", area.getId(), areaStations.size());
//
//                // 设置片区的热力站列表
//                area.setHeatStations(areaStations);
//                 // 创建一个按热力站ID分组的小区Map
//                Map<Long, List<CommunityInfo>> communitiesByStation = communities.stream()
//                        .filter(community -> community.getHeatId() != null)
//                        .collect(Collectors.groupingBy(CommunityInfo::getHeatId));
//                // 处理每个热力站的统计数据
//                for (HeatStation station : areaStations) {
//                    List<CommunityInfo> stationCommunities =communityInfoMapper.selectCommunityInfoLists(station.getId());
//                    System.err.println("热力站: " + station.getName() + ", ID: " + station.getId() + ", 关联小区数量: " + stationCommunities.size());
//                    if (stationCommunities.isEmpty()) {
//                        System.err.println("警告：热力站 " + station.getName() + " 没有关联的小区");
//                    } else {
//                        System.err.println("关联的小区: " + stationCommunities.stream()
//                                .map(CommunityInfo::getName)
//                                .collect(Collectors.joining(", ")));
//                    }
//
//                    // 计算热力站的统计数据
//                    TemperatureStats stationStats = calculateStationStats(stationCommunities, communityStats);
//
//                    // 设置热力站的统计数据
//                    station.setAverageTemperature(String.format("%.2f", stationStats.getAverageTemperature()));
//                    station.setStandardRate(String.format("%.2f", stationStats.getStandardRate()));
//                    station.setNonStandardRate(String.format("%.2f", stationStats.getNonStandardRate()));
//                }
//
//                // 如果没有热力站，设置默认值
//                if (areaStations.isEmpty()) {
//                    areaStations.forEach(station -> {
//                        station.setAverageTemperature("0.00");
//                        station.setStandardRate("0.00");
//                        station.setNonStandardRate("0.00");
//                    });
//                }
//            }
//
//            return areas;
//        } catch (Exception e) {
//            log.error("组装数据时发生错误", e);
//            return Collections.emptyList();
//        }
//    }

    private List<AreasInfo> assembleAreasData(
            List<AreasInfo> areas,
            List<HeatStation> stations,
            List<CommunityInfo> communities,
            Map<String, TemperatureStats> communityStats) {

        log.warn("开始组装数据 - 片区数量: {}, 热力站数量: {}, 小区数量: {}, 温度统计数量: {}",
                areas.size(), stations.size(), communities.size(), communityStats.size());

        try {
            // 1. 按片区ID分组热力站
            Map<Long, List<HeatStation>> stationsByArea = stations.stream()
                    .filter(station -> station.getAreaId() != null)
                    .collect(Collectors.groupingBy(station -> Long.parseLong(station.getAreaId())));

            // 2. 处理每个片区
            for (AreasInfo area : areas) {
                log.warn("处理片区: {}", area.getId());

                // 获取该片区的所有热力站
                Long id = area.getId();
                List<HeatStation> areaStations = heatStationMapper.selectHeatStationsByAreaId(id);
                log.warn("片区 {} 的热力站数量: {}", area.getId(), areaStations.size());

                // 设置片区的热力站列表
                area.setHeatStations(areaStations);

                // 创建一个按热力站ID分组的小区Map
                Map<Long, List<CommunityInfo>> communitiesByStation = communities.stream()
                        .filter(community -> community.getHeatId() != null)
                        .collect(Collectors.groupingBy(CommunityInfo::getHeatId));

                // 用于统计片区的总数据
                double areaTotalTemp = 0.0;
                double areaTotalStandardRate = 0.0;
                double areaTotalNonStandardRate = 0.0;
                int validStationCount = 0;  // 有效热力站计数（数据不为0的热力站）

                // 处理每个热力站的统计数据
                for (HeatStation station : areaStations) {
                    List<CommunityInfo> stationCommunities = communityInfoMapper.selectCommunityInfoLists(station.getId());
                    Long id1 = area.getId();
                    station.setAreaId(String.valueOf(id1));
                    System.err.println("热力站: " + station.getName() + ", ID: " + station.getId() +
                            ", 关联小区数量: " + stationCommunities.size());

                    if (stationCommunities.isEmpty()) {
                        System.err.println("警告：热力站 " + station.getName() + " 没有关联的小区");
                    } else {
                        System.err.println("关联的小区: " + stationCommunities.stream()
                                .map(CommunityInfo::getName)
                                .collect(Collectors.joining(", ")));
                    }

                    // 计算热力站的统计数据
                    TemperatureStats stationStats = calculateStationStats(stationCommunities, communityStats);

                    // 设置热力站的统计数据
                    station.setAverageTemperature(String.format("%.2f", stationStats.getAverageTemperature()));
                    station.setStandardRate(String.format("%.2f", stationStats.getStandardRate()));
                    station.setNonStandardRate(String.format("%.2f", stationStats.getNonStandardRate()));

                    // 如果热力站有有效数据（不为0），则计入片区统计
                    if (stationStats.getAverageTemperature() > 0) {
                        areaTotalTemp += stationStats.getAverageTemperature();
                        areaTotalStandardRate += stationStats.getStandardRate();
                        areaTotalNonStandardRate += stationStats.getNonStandardRate();
                        validStationCount++;
                    }
                }

                // 设置片区的统计数据（只计算有效热力站的平均值）
                if (validStationCount > 0) {
                    area.setAverageTemperature(String.format("%.2f", areaTotalTemp / validStationCount));
                    area.setStandardRate(String.format("%.2f", areaTotalStandardRate / validStationCount));
                    area.setNonStandardRate(String.format("%.2f", areaTotalNonStandardRate / validStationCount));

                    System.err.println("片区: " + area.getName() +
                            ", 有效热力站数量: " + validStationCount +
                            ", 平均温度: " + area.getAverageTemperature() +
                            ", 达标率: " + area.getStandardRate() +
                            ", 不达标率: " + area.getNonStandardRate());
                } else {
                    // 如果没有有效数据的热力站，则设置片区数据为0
                    area.setAverageTemperature("0.00");
                    area.setStandardRate("0.00");
                    area.setNonStandardRate("0.00");

                    System.err.println("片区: " + area.getName() + " 没有有效的热力站数据");
                }
            }

            return areas;
        } catch (Exception e) {
            log.error("组装数据时发生错误", e);
            e.printStackTrace();
            return Collections.emptyList();
        }
    }

    /**
     * 计算热力站的温度统计数据
     */
    private TemperatureStats calculateStationStats(
            List<CommunityInfo> communities,
            Map<String, TemperatureStats> communityStats) {

        if (communities.isEmpty()) {
            return new TemperatureStats(0.0, 0.0, 0.0);
        }

        double totalTemp = 0.0;
        double totalStandardRate = 0.0;
        double totalNonStandardRate = 0.0;
        int validCount = 0;

        for (CommunityInfo community : communities) {
            TemperatureStats stats = communityStats.get(community.getName());
            if (stats != null) {
                totalTemp += stats.getAverageTemperature();
                totalStandardRate += stats.getStandardRate();
                totalNonStandardRate += stats.getNonStandardRate();
                validCount++;
            }
        }

        if (validCount > 0) {
            return new TemperatureStats(
                    totalTemp / validCount,
                    totalStandardRate / validCount,
                    totalNonStandardRate / validCount
            );
        } else {
            return new TemperatureStats(0.0, 0.0, 0.0);
        }
    }

    @Data
    @AllArgsConstructor
    private static class TemperatureStats {
        private double averageTemperature;  // 平均温度
        private double standardRate;        // 达标率
        private double nonStandardRate;     // 不达标率
    }
}
